// @ts-check
import express from 'express';
import expressWs from 'express-ws';
import bodyParser from 'body-parser';

import { findReqHandler, getPathVariables, wsMap } from './requestManager.js';

import './api/hero.js';

const app = express();
expressWs(app);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

for (let [k, v] of wsMap) {
  /** @type {import('express-ws').WithWebsocketMethod} */ (/** @type {unknown} */ (app)).ws(k, v);
}

/** 请勿使用空的拦截，或单独/，这是默认拦截，将导致后面的ws 无法响应
 *  这里的解决方案是将 ws的配置挪到前面！
 */
app.use('/', function (req, res) {
  // 这里的 req.path会自动去掉 /api
  const path = req.path.replace(/\\/g, '/');
  const handler = findReqHandler({ method: req.method, path });
  if (!handler) {
    res.statusCode = 404;
    res.end();
    console.log(path, req.path);
  } else {
    const [{ path: pattern }, fn] = handler;
    const pathVars = getPathVariables(path, pattern);
    const result = fn({ query: req.query, body: req.body, pathVars });
    res.end(JSON.stringify(result));
  }
});

app.listen(1241, () => {
  console.log('server side: http://127.0.0.1:1241');
});
